{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from datetime import date, datetime\n",
    "from gs_quant.instrument import IRSwaption\n",
    "from gs_quant.common import BuySell, AggregationLevel, Currency\n",
    "from gs_quant.backtests.triggers import StrategyRiskTrigger, RiskTriggerRequirements, TriggerDirection\n",
    "from gs_quant.backtests.actions import AddTradeAction, ExitTradeAction\n",
    "from gs_quant.backtests.generic_engine import GenericEngine\n",
    "from gs_quant.backtests.strategy import Strategy\n",
    "from gs_quant.risk import Price, IRDelta\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize session\n",
    "from gs_quant.session import GsSession\n",
    "GsSession.use(client_id=None, client_secret=None, scopes=('run_analytics',)) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define backtest dates\n",
    "start_date = date(2021, 6, 1)\n",
    "end_date = datetime.today().date()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define instruments for strategy\n",
    "\n",
    "# USD swaption\n",
    "swaption = IRSwaption(expiration_date='6m', termination_date='10y', notional_currency=Currency.USD, \n",
    "                      buy_sell=BuySell.Sell, strike='=solvefor(25e3,bp)', name='swaption10y')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Start with USD swaption on start_date, rebalance when IR Delta breaches +75k"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define risk to hedge\n",
    "rebal_risk = IRDelta(aggregation_level=AggregationLevel.Type, currency='USD')\n",
    "\n",
    "# Define trade actions when breach\n",
    "action_exit = ExitTradeAction()\n",
    "action_add = AddTradeAction(swaption)\n",
    "\n",
    "# Define rebalance triggers\n",
    "trig_req = RiskTriggerRequirements(risk=rebal_risk, trigger_level=1e3, direction=TriggerDirection.ABOVE)\n",
    "# Order is important here, we first want to exit all positions in portfolio, then add the new trade\n",
    "trigger_risk = StrategyRiskTrigger(trig_req, [action_exit, action_add])\n",
    "\n",
    "# Starting with a swaption (first arg to Strategy), apply actions in order\n",
    "strategy = Strategy(swaption, trigger_risk)\n",
    "\n",
    "# Run backtest daily\n",
    "GE = GenericEngine()\n",
    "backtest = GE.run_backtest(strategy, start=start_date, end=end_date, frequency='1b', show_progress=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View results summary\n",
    "backtest.result_summary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View backtest trade ledger - this includes all trades that were added and removed excluding starting portfolio\n",
    "backtest.trade_ledger()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View Mark to Market\n",
    "pd.DataFrame({'Generic backtester': backtest.result_summary[Price]}).plot(figsize=(10, 6), title='Mark to market')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View Performance\n",
    "pd.DataFrame({'Generic backtester': backtest.result_summary['Cumulative Cash'] + backtest.result_summary[Price]}).plot(figsize=(10, 6), title='Performance')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}